package server

import (
	"errors"
	"net"
	"os"
	"os/exec"
)

// Graceful Restart server
// Reload self with args and fd
//
func GracefulRestart(listener net.Listener, args ...string) error {

	var file *os.File = nil
	var err error

	// get the listener type
	switch listener.(type) {
	case *net.TCPListener:
		tl := listener.(*net.TCPListener)
		file, err = tl.File()
	default:
		return errors.New("not support listener")
	}

	if err != nil {
		return err
	}

	// exec restart
	cmd := exec.Command(os.Args[0], args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	// put socket FD at the first entry
	cmd.ExtraFiles = []*os.File{file}

	return cmd.Start()
}
